package edu.sctu;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LENOVO on 2018/5/26.
 */
public class UserDatabase {
    public List<User> getUserList(){
        //数据库中存取数据保存在List集合中
        List<User> userList=new ArrayList<>();

        //3+1 读取数据库数据保存到List中
        Connection connection=null;
        Statement statement=null;
        ResultSet resultset=null;

        String sql="select* from t_users";
        //加载驱动程序
        try {
            Class.forName("com.mysql.jdbc.Driver");

            connection= DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/sctu_javaweb_2018?serverTimezone=UTC",
                    "root",
                    "123456"
            );
            statement=connection.createStatement();
            resultset=statement.executeQuery(sql);

            while(resultset.next()){
                int id=resultset.getInt(1);
                String name=resultset.getNString(2);
                String password=resultset.getNString(3);

                User user=new User();
                user.setId(id);
                user.setName(name);
                user.setPassword(password);

                userList.add(user);

            }
            resultset.close();
            statement.close();
            connection.close();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return  userList;

    }
}
